package com.example.ercmssystem2.controller;

import com.example.ercmssystem2.entity.TaskReport;
import com.example.ercmssystem2.entity.TaskReportPhoto;
import com.example.ercmssystem2.entity.User;
import com.example.ercmssystem2.service.TaskReportService;
import com.example.ercmssystem2.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 任务报告API控制器
 * 处理/api/completion相关的API请求
 */
@RestController
@RequestMapping("/api/completion")
@CrossOrigin(origins = "*")
public class TaskReportApiController {

    private final TaskReportService taskReportService;
    private final UserService userService;

    @Value("${app.upload.path:uploads}")
    private String uploadPath;

    @Autowired
    public TaskReportApiController(TaskReportService taskReportService, UserService userService) {
        this.taskReportService = taskReportService;
        this.userService = userService;
    }

    // 获取当前登录用户ID
    private Long getCurrentUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated()) {
            String username = authentication.getName();
            User user = userService.findByUsername(username);
            return user != null ? user.getId() : null;
        }
        return null;
    }

    // API路由 - 创建任务完成报告
    @PostMapping("")
    public ResponseEntity<?> createCompletionReport(@RequestBody Map<String, Object> request) {
        Long currentUserId = getCurrentUserId();
        if (currentUserId == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(Map.of("error", "用户未登录"));
        }

        Object eventIdObj = request.get("eventId");
        Object contentObj = request.get("content");

        if (eventIdObj == null || contentObj == null) {
            return ResponseEntity.badRequest().body(Map.of("error", "事件ID和报告内容不能为空"));
        }

        String content = contentObj.toString().trim();
        if (content.isEmpty()) {
            return ResponseEntity.badRequest().body(Map.of("error", "报告内容不能为空"));
        }

        try {
            Long eventId;
            if (eventIdObj instanceof Number) {
                eventId = ((Number) eventIdObj).longValue();
            } else {
                eventId = Long.parseLong(eventIdObj.toString());
            }
            
            TaskReport report = taskReportService.createCompletionReport(eventId, content, currentUserId);
            return ResponseEntity.status(HttpStatus.CREATED).body(Map.of(
                "success", true,
                "message", "报告提交成功",
                "data", report
            ));
        } catch (NumberFormatException e) {
            return ResponseEntity.badRequest().body(Map.of("error", "无效的事件ID: " + eventIdObj));
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(Map.of("error", e.getMessage()));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(Map.of("error", "服务器内部错误: " + e.getMessage()));
        }
    }

    // API路由 - 创建任务完成报告（包含照片）
    @PostMapping("/with-photos")
    public ResponseEntity<?> createCompletionReportWithPhotos(
            @RequestParam("eventId") Long eventId,
            @RequestParam("content") String content,
            @RequestParam(value = "photos", required = false) List<MultipartFile> photos,
            @RequestParam(value = "descriptions", required = false) List<String> descriptions) {
        
        Long currentUserId = getCurrentUserId();
        if (currentUserId == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(Map.of("error", "用户未登录"));
        }

        if (content == null || content.trim().isEmpty()) {
            return ResponseEntity.badRequest().body(Map.of("error", "报告内容不能为空"));
        }

        try {
            TaskReport report = taskReportService.createCompletionReportWithPhotos(eventId, content.trim(), currentUserId, photos, descriptions);
            return ResponseEntity.status(HttpStatus.CREATED).body(Map.of(
                "success", true,
                "message", "报告提交成功",
                "data", report
            ));
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(Map.of("error", e.getMessage()));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(Map.of("error", "服务器内部错误: " + e.getMessage()));
        }
    }

    // API路由 - 更新任务报告
    @PutMapping("/{reportId}")
    public ResponseEntity<?> updateReport(@PathVariable Long reportId, @RequestBody Map<String, Object> request) {
        Long currentUserId = getCurrentUserId();
        if (currentUserId == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(Map.of("error", "用户未登录"));
        }

        Object contentObj = request.get("content");
        if (contentObj == null) {
            return ResponseEntity.badRequest().body(Map.of("error", "报告内容不能为空"));
        }

        String content = contentObj.toString().trim();
        if (content.isEmpty()) {
            return ResponseEntity.badRequest().body(Map.of("error", "报告内容不能为空"));
        }

        try {
            TaskReport report = taskReportService.updateReport(reportId, content, currentUserId);
            return ResponseEntity.ok(Map.of(
                "success", true,
                "message", "报告修改成功",
                "data", report
            ));
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(Map.of("error", e.getMessage()));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(Map.of("error", "服务器内部错误: " + e.getMessage()));
        }
    }

    // API路由 - 更新任务报告（包含照片）
    @PutMapping("/{reportId}/with-photos")
    public ResponseEntity<?> updateReportWithPhotos(
            @PathVariable Long reportId,
            @RequestParam("content") String content,
            @RequestParam(value = "photos", required = false) List<MultipartFile> photos,
            @RequestParam(value = "descriptions", required = false) List<String> descriptions) {
        
        Long currentUserId = getCurrentUserId();
        if (currentUserId == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(Map.of("error", "用户未登录"));
        }

        if (content == null || content.trim().isEmpty()) {
            return ResponseEntity.badRequest().body(Map.of("error", "报告内容不能为空"));
        }

        try {
            TaskReport report = taskReportService.updateReportWithPhotos(reportId, content.trim(), currentUserId, photos, descriptions);
            return ResponseEntity.ok(Map.of(
                "success", true,
                "message", "报告修改成功",
                "data", report
            ));
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(Map.of("error", e.getMessage()));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(Map.of("error", "服务器内部错误: " + e.getMessage()));
        }
    }

    // API路由 - 获取事件的最新完成报告
    @GetMapping("/{eventId}")
    public ResponseEntity<?> getLatestCompletionReport(@PathVariable Long eventId) {
        try {
            TaskReport report = taskReportService.findLatestCompletionReport(eventId);
            if (report != null) {
                return ResponseEntity.ok(Map.of(
                    "success", true,
                    "data", report
                ));
            } else {
                return ResponseEntity.ok(Map.of(
                    "success", false,
                    "message", "未找到完成报告"
                ));
            }
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(Map.of("error", "服务器内部错误"));
        }
    }

    // API路由 - 获取事件的所有任务报告
    @GetMapping("/event/{eventId}/reports")
    public ResponseEntity<?> getTaskReportsByEventId(@PathVariable Long eventId) {
        try {
            List<TaskReport> reports = taskReportService.findByEventId(eventId);
            
            // 为每个报告添加报告人姓名
            List<Map<String, Object>> reportsWithNames = new ArrayList<>();
            for (TaskReport report : reports) {
                Map<String, Object> reportData = Map.of(
                    "id", report.getId(),
                    "content", report.getContent(),
                    "reportTime", report.getReportTime(),
                    "reportedBy", report.getReportedBy(),
                    "reporterName", report.getReportedBy() != null ? 
                        userService.findById(report.getReportedBy()).getRealName() : "未知用户",
                    "photos", report.getPhotos() != null ? report.getPhotos() : new ArrayList<>()
                );
                reportsWithNames.add(reportData);
            }
            
            return ResponseEntity.ok(Map.of(
                "success", true,
                "data", reportsWithNames
            ));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(Map.of("error", "服务器内部错误: " + e.getMessage()));
        }
    }

    // API路由 - 获取所有报告（管理用）
    @GetMapping("/reports")
    public ResponseEntity<?> getAllReports(
            @RequestParam(required = false) Long eventId,
            @RequestParam(required = false) Long reporterId,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate,
            @RequestParam(required = false) String timeRange,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "12") int size) {
        try {
            // 构建时间范围
            LocalDateTime start = null;
            LocalDateTime end = null;
            
            if (timeRange != null) {
                LocalDateTime now = LocalDateTime.now();
                switch (timeRange) {
                    case "today":
                        start = now.toLocalDate().atStartOfDay();
                        end = now.toLocalDate().atTime(23, 59, 59);
                        break;
                    case "week":
                        start = now.toLocalDate().minusDays(now.getDayOfWeek().getValue() - 1).atStartOfDay();
                        end = now.toLocalDate().atTime(23, 59, 59);
                        break;
                    case "month":
                        start = now.toLocalDate().withDayOfMonth(1).atStartOfDay();
                        end = now.toLocalDate().atTime(23, 59, 59);
                        break;
                }
            } else if (startDate != null && endDate != null) {
                start = LocalDateTime.parse(startDate + "T00:00:00");
                end = LocalDateTime.parse(endDate + "T23:59:59");
            }
            
            // 获取报告列表
            List<TaskReport> reports = taskReportService.findReportsWithFilters(eventId, reporterId, start, end, page, size);
            long totalElements = taskReportService.countReportsWithFilters(eventId, reporterId, start, end);
            
            // 为每个报告添加报告人姓名和事件ID
            List<Map<String, Object>> reportsWithNames = new ArrayList<>();
            for (TaskReport report : reports) {
                Map<String, Object> reportData = Map.of(
                    "id", report.getId(),
                    "eventId", report.getEvent().getId(),
                    "content", report.getContent(),
                    "reportTime", report.getReportTime(),
                    "reportedBy", report.getReportedBy(),
                    "reporterName", report.getReportedBy() != null ? 
                        userService.findById(report.getReportedBy()).getRealName() : "未知用户",
                    "photos", report.getPhotos() != null ? report.getPhotos() : new ArrayList<>()
                );
                reportsWithNames.add(reportData);
            }
            
            Map<String, Object> response = new HashMap<>();
            response.put("content", reportsWithNames);
            response.put("totalElements", totalElements);
            response.put("totalPages", (int) Math.ceil((double) totalElements / size));
            response.put("currentPage", page);
            response.put("size", size);
            
            return ResponseEntity.ok(Map.of(
                "success", true,
                "data", response
            ));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(Map.of("error", "服务器内部错误: " + e.getMessage()));
        }
    }

    // API路由 - 获取单个报告详情
    @GetMapping("/reports/{reportId}")
    public ResponseEntity<?> getReportById(@PathVariable Long reportId) {
        try {
            TaskReport report = taskReportService.findById(reportId);
            if (report == null) {
                return ResponseEntity.notFound().build();
            }
            
            Map<String, Object> reportData = Map.of(
                "id", report.getId(),
                "eventId", report.getEvent().getId(),
                "content", report.getContent(),
                "reportTime", report.getReportTime(),
                "reportedBy", report.getReportedBy(),
                "reporterName", report.getReportedBy() != null ? 
                    userService.findById(report.getReportedBy()).getRealName() : "未知用户",
                "photos", report.getPhotos() != null ? report.getPhotos() : new ArrayList<>()
            );
            
            return ResponseEntity.ok(Map.of(
                "success", true,
                "data", reportData
            ));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(Map.of("error", "服务器内部错误: " + e.getMessage()));
        }
    }

    // API路由 - 删除报告
    @DeleteMapping("/reports/{reportId}")
    public ResponseEntity<?> deleteReport(@PathVariable Long reportId) {
        Long currentUserId = getCurrentUserId();
        if (currentUserId == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(Map.of("error", "用户未登录"));
        }

        try {
            taskReportService.deleteReport(reportId);
            return ResponseEntity.ok(Map.of(
                "success", true,
                "message", "报告删除成功"
            ));
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(Map.of("error", e.getMessage()));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(Map.of("error", "服务器内部错误: " + e.getMessage()));
        }
    }

    // API路由 - 获取报告统计信息
    @GetMapping("/statistics")
    public ResponseEntity<?> getReportStatistics() {
        try {
            Map<String, Object> statistics = taskReportService.getReportStatistics();
            return ResponseEntity.ok(Map.of(
                "success", true,
                "data", statistics
            ));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(Map.of("error", "服务器内部错误: " + e.getMessage()));
        }
    }

    // API路由 - 获取报告照片
    @GetMapping("/{reportId}/photos")
    public ResponseEntity<?> getReportPhotos(@PathVariable Long reportId) {
        try {
            List<TaskReportPhoto> photos = taskReportService.getReportPhotos(reportId);
            return ResponseEntity.ok(Map.of(
                "success", true,
                "data", photos
            ));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(Map.of("error", "服务器内部错误"));
        }
    }

    // API路由 - 上传照片
    @PostMapping("/{reportId}/photos")
    public ResponseEntity<?> uploadPhoto(
            @PathVariable Long reportId,
            @RequestParam("photo") MultipartFile photo,
            @RequestParam(value = "description", required = false) String description) {
        
        Long currentUserId = getCurrentUserId();
        if (currentUserId == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(Map.of("error", "用户未登录"));
        }

        if (photo == null || photo.isEmpty()) {
            return ResponseEntity.badRequest().body(Map.of("error", "请选择要上传的照片"));
        }

        try {
            TaskReportPhoto uploadedPhoto = taskReportService.uploadPhoto(reportId, photo, description, currentUserId);
            return ResponseEntity.ok(Map.of(
                "success", true,
                "message", "照片上传成功",
                "data", uploadedPhoto
            ));
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(Map.of("error", e.getMessage()));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(Map.of("error", "服务器内部错误: " + e.getMessage()));
        }
    }

    // API路由 - 删除照片
    @DeleteMapping("/photos/{photoId}")
    public ResponseEntity<?> deletePhoto(@PathVariable Long photoId) {
        Long currentUserId = getCurrentUserId();
        if (currentUserId == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(Map.of("error", "用户未登录"));
        }

        try {
            taskReportService.deletePhoto(photoId, currentUserId);
            return ResponseEntity.ok(Map.of(
                "success", true,
                "message", "照片删除成功"
            ));
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(Map.of("error", e.getMessage()));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(Map.of("error", "服务器内部错误: " + e.getMessage()));
        }
    }

    // API路由 - 获取照片文件
    @GetMapping("/photos/{photoId}/file")
    public ResponseEntity<?> getPhotoFile(@PathVariable Long photoId) {
        try {
            // 直接从数据库查找照片
            TaskReportPhoto photo = taskReportService.getPhotoById(photoId);
            
            if (photo == null) {
                return ResponseEntity.notFound().build();
            }

            Path filePath = Paths.get(photo.getFilePath());
            if (!Files.exists(filePath)) {
                return ResponseEntity.notFound().build();
            }

            byte[] fileContent = Files.readAllBytes(filePath);
            
            // 处理文件名编码问题，避免中文字符导致的HTTP头错误
            String fileName = photo.getFileName();
            String safeFileName;
            try {
                // 尝试URL编码文件名
                safeFileName = java.net.URLEncoder.encode(fileName, "UTF-8");
            } catch (Exception e) {
                // 如果编码失败，使用安全的文件名
                safeFileName = "photo_" + photoId + ".jpg";
            }
            
            return ResponseEntity.ok()
                    .header("Content-Type", photo.getContentType())
                    .header("Content-Disposition", "inline; filename=\"" + safeFileName + "\"")
                    .body(fileContent);
        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(Map.of("error", "文件读取失败"));
        }
    }
} 